<template>
  <el-dialog title="流量充值" v-model="state.dialogVisible" width="500" center>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      @submit.native.prevent
      v-loading="state.loading"
    >
      <el-form-item label="充值金额" prop="price">
        <el-input
          v-model="form.price"
          placeholder="请输入充值金额"
          type="number"
          @change="form.price = Math.floor(form.price * 100) / 100"
        >
          <template #append>元</template>
        </el-input>
        <div>
          流量单价：{{ state.trafficUnitPrice }}元/GB
          <span v-if="form.price">，预计{{ resGB }}GB</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { postShopRecharge, postDictGetInfoByName } from '@/api/business'

const emits = defineEmits(['ok'])

const state = reactive({
  dialogVisible: false,
  trafficUnitPrice: 0.1,
  shopId: '',
  loading: false,
  minPrice: 0.01
})

const formRef = ref()
const form = reactive({})

function validatePrice(rule, value, callback) {
  if (value) {
    if (value >= state.minPrice) {
      callback()
    } else {
      callback(new Error(`金额不能小于${state.minPrice}`))
    }
  } else {
    callback(new Error('请输入金额'))
  }
}
const rules = reactive({
  price: [{ required: true, validator: validatePrice, trigger: 'blur' }]
})

const resGB = computed(() => {
  return Math.floor((form.price / state.trafficUnitPrice) * 100) / 100
})

function close() {
  state.dialogVisible = false
  formRef.value.resetFields()
}
function handleSubmit() {
  formRef.value.validate((valid) => {
    if (valid) {
      state.loading = true
      postShopRecharge({
        price: form.price,
        trafficUnitPrice: state.trafficUnitPrice,
        shopId: state.shopId
      })
        .then((res) => {
          ElMessage({
            message: '充值成功',
            type: 'success'
          })
          emits('ok')
          close()
        })
        .finally(() => {
          state.loading = false
        })
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

const getMinPrice = () => {
  state.loading = true
  postDictGetInfoByName({ dictName: 'ACCOUNT_MIN' })
    .then((res) => {
      state.minPrice = res.data[0]?.dictValue || 0.01
    })
    .finally(() => {
      state.loading = false
    })
}

function show(data) {
  state.dialogVisible = true
  state.trafficUnitPrice = data.trafficUnitPrice
  state.shopId = data.shopId
  getMinPrice()
}

defineExpose({ show })
</script>
